#include <glf.h>
#include <glfwindow.h>
#include <glfu.h>

//GL program handle
static GLuint programHandle = 0;

//Vertex attribute location
static GLint vertexLocation = -1;

//Draw program attributes
static const int programAttributes[]=
{ 
	GL_VERTEX_SHADER, (int)"draw.vert", 
	GL_FRAGMENT_SHADER, (int)"draw.frag", 
	0 
};

//Vertex data
static const float	positions[6]={
	0,-0.5f,
	0.5f,0.5f,
	-0.5f,0.5f
};

static void initialise(void* userdata)
{
	programHandle = glfuLoadProgram( programAttributes );
	if( programHandle != 0 )
	{
		glUseProgram( programHandle );
		vertexLocation = glGetAttribLocation( programHandle, "vertex" );
		if( vertexLocation != -1 )
		{
			glEnableVertexAttribArray( vertexLocation );
			glVertexAttribPointer( vertexLocation, 2, GL_FLOAT, GL_FALSE, 0, positions );
		}
	}
}

static void terminate(void* userdata)
{
	if( vertexLocation != -1 )
	{
		glVertexAttribPointer( vertexLocation, 0, 0, 0, 0, 0 );
		glDisableVertexAttribArray( vertexLocation );
		vertexLocation =-1;
	}
	if( programHandle != 0 )
	{
		glUseProgram( 0 );
		glfuUnloadProgram( programHandle );
		programHandle = 0;
	}
}

static void think(void* userdata)
{
}

static void render(void* userdata)
{
	glClear(GL_COLOR_BUFFER_BIT);
	glDrawArrays( GL_TRIANGLES, 0, 3 );
}

static void resize(void* userdata)
{
	glViewport(0,0,glfGetWidth(),glfGetHeight());
}

int main(void)
{

	glfConfigSetAttribute(glfMajorVersion, 3);
	glfConfigSetAttribute(glfMinorVersion, 1);
	glfConfigSetAttribute(glfContextFlags, glfContextForwardCompatible);

	if( !glfCreateWindow( "Draw", 640, 480 ) )
	{
		return -1;
	}
	
	glfSetCallBack(glfCallbackInitialise, initialise, NULL );
	glfSetCallBack(glfCallbackThink, think, NULL );
	glfSetCallBack(glfCallbackRender, render, NULL );
	glfSetCallBack(glfCallbackResize, resize, NULL );
	glfSetCallBack(glfCallbackTerminate, terminate, NULL );

	if( !glfMainloop() )
	{
		return -1;
	}

	glfDestroyWindow();

	return 0;
}
